package com.talkyun.openx.interceptor;

import java.util.ArrayList;
import java.util.List;

public class URIMain {

    private static String[] splitIgnoreBlank(String src, String split) {
        if (isBlank(src)) {
            return new String[0];
        }

        String[] parts = src.split("/");
        List<String> result = new ArrayList<String>(parts.length);
        for (String p : parts) {
            if (isBlank(p)) {
                continue;
            }
            result.add(p.trim());
        }
        return result.toArray(new String[result.size()]);
    }

    private static boolean isBlank(String s) {
        return s == null || s.trim().length() == 0;
    }

    private static String getLastUri(String uri, String ctx) {
        String[] tmp = splitIgnoreBlank(ctx, "/");
        String fineCtx = tmp.length == 0 ? "" : tmp[0];

        String[] parts = splitIgnoreBlank(uri, "/");
        if (parts.length == 0 || (parts.length == 1 && parts[0].equals(fineCtx))) {
            return "/";
        }

        StringBuilder sb = new StringBuilder();
        for (int x = (parts[0].equals(fineCtx) ? 1 : 0); x < parts.length; x++) {
            sb.append("/").append(parts[x]);
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        String ctx = "ctx/";
        String uri = "/ctx/sso///// RoleService/listByName";

        System.out.println("--> " + getLastUri(uri, ctx));
    }
}
